﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using SCM.Model.DBEntity;
using SCM.Servie.IBusiness;

namespace SCM.Manage.Controllers
{
    [Authorize]
    public class BasicRuleController : BaseController
    {
        #region 法规
        public IActionResult Index()
        {
            return View();
        }

        #region 添加
        public ActionResult AddView()
        {
            return View();
        }

        public IActionResult Add(T_Rule entity)
        {
            #region 数据验证
            if (string.IsNullOrWhiteSpace(entity.RuleName))
            {
                return Error("名称不能为空");
            }
            #endregion
            entity.ID = Guid.NewGuid().ToString();
            entity.Creator = CurrentUserId;
            entity.CreatorName = CurrentUserName;

            var service = GetService<IRuleService>();
            bool result = service.Add(entity) != null ? true : false;
            return result ? GetOk(result) : Error("保存失败");
        }
        #endregion

        #region 查询
        [HttpPost]
        public IActionResult Search(string ruleName, int index = 1)
        {
            var service = GetService<IRuleService>();
            var userPage = service.Query(ruleName, new Common.PageInfo() { PageIndex = index, PageSize = 10 });
            return GetOk(new { totalCount = userPage.Page.DataCount, items = userPage.Data });
        }

        #endregion

        #region 编辑
        public IActionResult EditView(string id)
        {
            var model = GetService<IRuleService>().GetById(id);
            return View(model);
        }

        public IActionResult Modify(T_Rule entity)
        {
            entity.ModifyUserId = CurrentUserId;
            entity.ModifyUserName = CurrentUserName;

            bool result = GetService<IRuleService>().Update(entity);
            return result ? GetOk(result) : Error("保存失败");
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除  【支持批量操作】
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public IActionResult Delete(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids) || ids.Split(',').Length < 0)
            {
                return Error("请选择数据");
            }
            var delIds = ids.Split(',').ToList();
            bool result = GetService<IRuleService>().Delete(delIds);
            return result ? GetOk(result) : Error("删除失败");
        }
        #endregion
        #endregion

        #region 法规条目
        private void BindRule()
        {
            List<SelectListItem> ruleList = new List<SelectListItem>();
            ruleList.Add(new SelectListItem() { Text = "请选择", Value = "", Selected = true });

            var service = GetService<IRuleService>();
            var rules = service.GetList("");
            rules.ForEach(item =>
            {
                ruleList.Add(new SelectListItem() { Text = item.RuleName, Value = item.ID });
            });

            ViewBag.RuleList = ruleList;
        }

        public IActionResult RuleItemIndex()
        {
            BindRule();
            return View();
        }

        #region 添加
        public ActionResult AddRuleItemView()
        {
            BindRule();
            return View();
        }

        public IActionResult AddRuleItem(T_RuleItem entity)
        {
            #region 数据验证
            if (string.IsNullOrWhiteSpace(entity.RuleID))
            {
                return Error("请选择所属规则");
            }
            if (string.IsNullOrWhiteSpace(entity.CASNo) && string.IsNullOrWhiteSpace(entity.ECNo))
            {
                return Error("CAS号与EC号不能同时为空");
            }
            #endregion
            entity.ID = Guid.NewGuid().ToString();
            var service = GetService<IRuleItemService>();
            bool result = service.Add(entity) != null ? true : false;
            return result ? GetOk(result) : Error("保存失败");
        }
        #endregion

        #region 查询
        [HttpPost]
        public IActionResult SearchRuleItem(string ruleId, string casNo, string ecNO, string cName, string eName, int index = 1)
        {
            var service = GetService<IRuleItemService>();
            var userPage = service.Query(ruleId, casNo, ecNO, cName, eName, new Common.PageInfo() { PageIndex = index, PageSize = 10 });
            return GetOk(new { totalCount = userPage.Page.DataCount, items = userPage.Data });
        }

        #endregion

        #region 编辑
        public IActionResult EditRuleItemView(string id)
        {
            BindRule();
            var model = GetService<IRuleItemService>().GetById(id);
            return View(model);
        }

        public IActionResult ModifyRuleItem(T_RuleItem entity)
        {
            bool result = GetService<IRuleItemService>().Update(entity);
            return result ? GetOk(result) : Error("保存失败");
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除  【支持批量操作】
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public IActionResult DeleteRuleItem(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids) || ids.Split(',').Length < 0)
            {
                return Error("请选择数据");
            }
            var delIds = ids.Split(',').ToList();
            bool result = GetService<IRuleItemService>().Delete(delIds);
            return result ? GetOk(result) : Error("删除失败");
        }
        #endregion

        #region 导入
        public IActionResult RuleItemImportView(string id)
        {
            ViewBag.RuleID = id;
            return View();
        }

        [HttpPost]
        public IActionResult RuleItemImport(string ruleId)
        {
            try
            {
                if (Request.Form.Files == null || Request.Form.Files.Count <= 0)
                {
                    return Error("请选择您要导入的文件!");
                }

                var excelFile = Request.Form.Files[0];
                string fileType = excelFile.ContentType;
                string fileName = excelFile.FileName.ToLower();
                string fileExt = Path.GetExtension(fileName);
                string fileAllowExt = "*.xlsx;*.xls";

                if (fileAllowExt.IndexOf(fileExt) < 0)
                {
                    return Error("请选择正确格式的Excel文件!");
                }

                #region 解析文件

                DataTable FileSource = NPOIHelper.ImportExceltoDt(excelFile.OpenReadStream());
                #endregion

                //保存解析数据集合
                List<T_RuleItem> ruleItemImport = new List<T_RuleItem>();
                foreach (var item in FileSource.AsEnumerable())
                {
                    string casNo = item.Field<string>("CAS no");
                    string ecNo = item.Field<string>("EC / List no");

                    //casNo与ecNo 均为空，则跳过
                    if ((string.IsNullOrWhiteSpace(casNo) || casNo.Trim().Equals("-")) &&
                        (string.IsNullOrWhiteSpace(ecNo) || ecNo.Trim().Equals("-")))
                        continue;

                    T_RuleItem model = new T_RuleItem();
                    model.ID = Guid.NewGuid().ToString();
                    model.RuleID = ruleId;
                    model.CASNo = casNo;
                    model.ECNo = ecNo;
                    model.CName = item.Field<string>("Substance Name CN");
                    model.Ename = item.Field<string>("Substance Name EN");
                    model.Remark = item.Field<string>("Regulation Remarks");

                    string thresholdStr = item.Field<string>("Threshold");
                    decimal threshold = 0;
                    if (!string.IsNullOrWhiteSpace(thresholdStr))
                    {
                        if (thresholdStr.Contains("%"))
                        {
                            thresholdStr = thresholdStr.Replace("%", "");
                        }
                        decimal.TryParse(thresholdStr, out threshold);
                    }
                    model.Value = threshold;

                    ruleItemImport.Add(model);
                }

                if (ruleItemImport != null && ruleItemImport.Count > 0)
                {
                    bool result = GetService<IRuleItemService>().SaveOrUpdate(ruleId, ruleItemImport);
                    return result ? GetOk(result) : Error("导入失败");
                }

                return GetOk("导入成功");
            }
            catch (Exception ex)
            {
                return Error("导入失败，信息：" + ex.Message);
            }
        }

        #endregion
        #endregion
    }
}
